package com.fly.web.controller.system;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.fly.system.model.UserModel;
import com.fly.system.service.UserService;
import com.google.common.collect.Sets;
import com.google.common.collect.Sets.SetView;

import jdk.management.resource.internal.inst.SocketOutputStreamRMHooks;

@Controller
public class LoginController {
	
	@Autowired
	private UserService user;
	
	@GetMapping("/login")
	public String index(){
		return "login";
	}
	
	@PostMapping("/login")
	@ResponseBody
	public JSONObject login(UserModel user){
		UsernamePasswordToken token = new UsernamePasswordToken(user.getLoginName(), user.getPassword());
        Subject subject = SecurityUtils.getSubject();
        JSONObject json = new JSONObject();
		try {
            //进行验证，这里可以捕获异常，然后返回对应信息
            subject.login(token);
            json.put("code",0);
            json.put("msg","成功");
            return json;
//            subject.checkRole("admin");
//            subject.checkPermissions("query", "add");
        } catch (AuthenticationException e) {
            e.printStackTrace();
            json.put("msg","账号或密码错误");
            return json;
        } catch (AuthorizationException e) {
            e.printStackTrace();
            json.put("msg","没有权限");
            return json;
        }
	}
	
	
	@RequiresRoles("admin")
    @RequiresPermissions("system:user:view")
    @RequestMapping("/index")
	@ResponseBody
    public String index1() {
		List<UserModel> list = user.finAll();
		list.forEach(u->System.out.println(u.getUserName()));
        return "index!";
    }
	
	
	public static void main(String[] args) {
		List<String> list1 = new ArrayList<String>();
		List<String> list2 = new ArrayList<String>();
		list1.add("1");
		list1.add("2");
		
		list2.add("3");
		list2.add("2");
		
		boolean b = list1.retainAll(list2);
		SetView<String> view = Sets.intersection(Sets.newHashSet(list1), Sets.newHashSet(list2));
		for (String string : view) {
			System.out.println(string);
		}
	}
	
}
